const router = require('koa-router')()
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const exec = require('child_process').exec;
const ffmpeg = require('fluent-ffmpeg');
const spawn = require('child_process').spawn;
const db = require('../db/initdb');



router.prefix('/aaa')

router.get('/', async (ctx, next) => {
    ctx.body = 'this is a creator response!'
})

router.get('/videoName', async (ctx, next) => {
    let sql = "select hs.card.image from hs.card where hs.card.id=$1";
    let result = await db.query(sql, [ctx.query.id]);
    console.log(result)

    ctx.body = JSON.stringify(result.rows);
})

router.get('/video', async (ctx, next) => {

    let videoPath = path.join(__dirname, `../public/images/${ctx.query.name}`);
    let videoContent = fs.readFileSync(videoPath);
    let mimeType = mime.lookup(videoPath);

    ctx.set('content-type', mimeType); //设置返回类型

    ctx.body = videoContent;


})

router.post('/recoding', async (ctx, next) => {
    const file = ctx.request.files.file // 获取上传的文件
    const reader = fs.createReadStream(file.filepath) // 创建可读流
    const ext = file.originalFilename.split('.')[2] // 获取文件后缀
    const fileName = `${Date.now()}.${ext}` // 重命名文件
    const filePath = path.join(__dirname, '../voice', fileName) // 文件保存路径

    const writer = fs.createWriteStream(filePath) // 创建可写流
    reader.pipe(writer) // 将可读流通过管道写入可写流

    ctx.body = '上传成功'
})

router.post('/merge', async (ctx, next) => {
    const file = ctx.request.files.file // 获取上传的文件
    const fileName = `${Date.now()}.mp4` // 重命名文件

    // 视频路径
    const videoPath = path.join(__dirname, '../video/1_154884390000161.mp4');
    // 音频路径
    // const audioPath = path.join(__dirname, '../voice/岑宁儿-追光者.mp3');
    const audioPath = file.filepath;
    // 输出文件路径
    const outputPath = path.join(__dirname, '../output', fileName);

    const ffmpeg = spawn('ffmpeg', ['-i', audioPath, '-i', videoPath, '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental', outputPath]);

    // 监听 ffmpeg 进程的输出信息
    ffmpeg.stderr.on('data', (data) => {
        console.log(` ${data} `);
    });

    ffmpeg.on('close', (code) => {
        console.log(`  ffmpeg exit with code ${code} `);

        // 将合成的文件作为响应返回
        ctx.body = {
            code: 200,
            message: '合成成功',
        };
    });


})


router.get('/bbb', async (ctx, next) => {
    const videoPath = path.join(__dirname, '../public/images/伪装者-你敢开枪吗.mp4');
    const outputPath = path.join(__dirname, '../output', 'a.srt');
    const ffmpeg = spawn('ffmpeg', ['-i', videoPath, '-map', '0:s:0', outputPath]);
    // 监听 ffmpeg 进程的输出信息
    ffmpeg.stderr.on('data', (data) => {
        console.log(` ${data} `);
    });

    ffmpeg.on('close', (code) => {
        console.log(`  ffmpeg exit with code ${code} `);

        // 将合成的文件作为响应返回
        ctx.body = {
            code: 200,
            message: '合成成功',
        };
    });
})

module.exports = router
